package com.computer.network.security.handler;

import com.alibaba.fastjson.JSON;
import com.computer.network.security.ex.CustomSecurityException;
import com.computer.network.util.Result;
import com.computer.network.util.ResultCode;
import org.springframework.security.authentication.*;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.charset.StandardCharsets;

/**
 * 登录失败处理器
 *
 * @Author cgs
 * @Date 2022/8/19 11:33
 */
@Component
public class LoginFailureHandler implements AuthenticationFailureHandler {
    @Resource
    Result result;
    @Resource
    ResultCode resultCode;

    @Override
    public void onAuthenticationFailure(HttpServletRequest httpServletRequest,
                                        HttpServletResponse httpServletResponse,
                                        AuthenticationException e)
            throws IOException, ServletException {
        String message = null;
        //设置编码格式
        httpServletResponse.setContentType("application/json;charset=utf-8");
        //获取输入流
        ServletOutputStream outputStream = httpServletResponse.getOutputStream();
        if (e instanceof AccountExpiredException) {
            message = "账户过期，登录失败";
        } else if (e instanceof BadCredentialsException) {
            message = "用户名或密码错误，请重新登录";
        } else if (e instanceof DisabledException) {
            message = "账户已被禁用，登录失败";
        } else if (e instanceof LockedException) {
            message = "账户已被锁定，登录失败";
        } else if (e instanceof InternalAuthenticationServiceException) {
            message = "账户不存在，请重新登录";
        } else if (e instanceof CustomSecurityException) {
            message = e.getMessage();
        } else {
            message = "发生未知异常，登录失败";
        }
        Result error = result.error(resultCode.ERROR, message);
        String result2 = JSON.toJSONString(error);
        //输出流
        outputStream.write(result2.getBytes(StandardCharsets.UTF_8));
        //清空缓存区
        outputStream.flush();
        //关闭缓存
        outputStream.close();
    }
}
